package com.example.week7homework;

import android.os.Bundle;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class SqlLite extends Activity {

    public StudentDao studentDao;

    EditText txtStuNo,txtName,txtClazz;
    Button addBtn,updateBtn,queryBtn;
    ListView dataList;
    List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
    SimpleAdapter adapter;


    //因为getWritableDatabase内部调用了context.openOrCreateDatabase(name,0,factory);
    //为确保context已初始化,我们可以把实例化Dao的步骤放在Activity的onCreate里
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sql_lite);

        txtStuNo = (EditText)findViewById(R.id.c84txtStuNo);
        txtName = (EditText)findViewById(R.id.c84txtName);
        txtClazz = (EditText)findViewById(R.id.c84txtClazz);

        addBtn = (Button)findViewById(R.id.c84btnAdd);
        updateBtn = (Button)findViewById(R.id.c84btnUpdate);
        queryBtn = (Button)findViewById(R.id.c84btnQuery);

        dataList =(ListView)findViewById(R.id.c84dataList);

        OnClickListener oc =new ViewOnClickListener();
        addBtn.setOnClickListener(oc);
        updateBtn.setOnClickListener(oc);
        queryBtn.setOnClickListener(oc);

        studentDao = new StudentDao(new StudentDBHelper(SqlLite.this));
        //初始状态默认查询全部
        String sql = " select * from student order by publish desc";
        studentDao.execQuery(list,sql);
        adapter = new SimpleAdapter(
                this,
                list,
                R.layout.c8_listview_item,
                new String[]{"stu_no","name","clazz","publish"},
                new int[]{R.id.c84stuNo,R.id.c84stuName, R.id.c84clazz, R.id.c84publish}
        );
        dataList.setAdapter(adapter);
        //为listView列表注册数据项监听器
        dataList.setOnItemClickListener(new OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
                                    long arg3) {
                Map map =list.get(pos);
                int sid = (Integer) map.get("sid");
                String stuNo = String.valueOf(map.get("stu_no"));
                String msg ="您确定要删除姓名为"+stuNo+"的学生吗？";
                createAlertDialog(msg, sid).show();
            }
        });
    }
    /**根据sid删除一个学生记录*/
    private void deleteStu(int sid){
        String sql = "delete from student where sid="+sid;
        studentDao.execSQL(sql);
        refreshDataList();
    }
    /**定义适用三个按钮的监听器类*/
    class ViewOnClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            String strSQL;
            boolean flag;

            switch (v.getId()) {
                case R.id.c84btnAdd:
                    addStudent();
                    break;

                case R.id.c84btnQuery:
                    refreshDataList();
                    break;

                case R.id.c84btnUpdate:

                    break;
            }
        }
    }

    private void addStudent(){
        String stuNo = txtStuNo.getText().toString().trim();
        String name = txtName.getText().toString().trim();
        String clazz = txtClazz.getText().toString().trim();
        String publish = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        if("".equals(stuNo)||"".equals(name)||"".equals(clazz)){
            Toast.makeText(getApplicationContext(), "请填写完整数据！", Toast.LENGTH_SHORT).show();
            return ;
        }
        // 动态组件SQL语句
        String strSQL = "insert into student values(null,'" + stuNo + "','"
                + name + "','" + clazz + "','" + publish + "')";
        boolean flag = studentDao.execSQL(strSQL);
        txtStuNo.setText("");
        txtName.setText("");
        txtClazz.setText("");
        //返回信息
        String message = flag?"添加成功":"添加失败";
        refreshDataList();
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }
    //根据查询条件刷新列表数据
    private void refreshDataList(){
        String stuNo = txtStuNo.getText().toString().trim();
        String name = txtName.getText().toString().trim();
        String clazz = txtClazz.getText().toString().trim();
        String strSQL = "select * from student where 1=1 " ;
        if(!"".equals(stuNo)){
            strSQL+=" and stu_no like '%"+stuNo+"%'";
        }
        if(!"".equals(name)){
            strSQL+=" and name like '%"+name+"%'";
        }
        if(!"".equals(clazz)){
            strSQL+=" and clazz like '%"+clazz+"%'";
        }
        strSQL+=" order by publish desc";
        studentDao.execQuery(list,strSQL);
        adapter.notifyDataSetChanged();//只有当适配器数据容器中的值发生变化时，它才会触发uI的刷新；
    }

    /**生成信息交互对话框！    */
    private AlertDialog createAlertDialog(String msg, final int sid){
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setIcon(R.mipmap.ic_launcher)//设置标题的图片
                .setTitle("删除联系人")//设置对话框的标题
                .setMessage(msg)//设置对话框的内容
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        deleteStu(sid);
                    }
                }).create();
        return dialog;
    }
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if(this.studentDao!=null){//关闭数据库
            SQLiteDatabase db = this.studentDao.getDB();
            if(db!=null )
                db.close();
        }
    }


}